package main

import (
	"fmt"
	"strconv"

	"gopkg.in/ini.v1"
)

var ServerCfg *Config = nil

type ConfigSvr struct {
	ListenAddr string
	Port       string
}

type ConfigCli struct {
	ShutdownTime string
	LunXunTime   int
}

type Config struct {
	SvrCfg *ConfigSvr

	CliCfg *ConfigCli
}

func StrToInt(s string) int {

	i, e := strconv.Atoi(s)

	if e != nil {
		i = -1
	}

	return i

}

func NewConfig(inipath string) *Config {
	/*
		conf := goini.SetConfig(inipath)
		return &Config{
			SvrCfg: &ConfigSvr{
				ListenAddr: conf.GetValue("server", "listenaddr"),
				Port:       conf.GetValue("server", "port"),
			},
			CliCfg: &ConfigCli{
				ShutdownTime: conf.GetValue("client", "shutdowntime"),
				LunXunTime:   StrToInt(conf.GetValue("client", "lunxuntime")),
			},
		}
	*/
	inifile, _ := ini.Load(inipath)

	section, _ := inifile.GetSection("server")
	clisection, _ := inifile.GetSection("client")
	return &Config{
		SvrCfg: &ConfigSvr{
			ListenAddr: section.Key("listenaddr").String(),
			Port:       section.Key("port").String(),
		},
		CliCfg: &ConfigCli{
			ShutdownTime: clisection.Key("shutdowntime").String(),
			LunXunTime:   clisection.Key("lunxuntime").MustInt(),
		},
	}
}

type IndexPageObj struct {
	Date   string `json:"date"`
	Time   string `json:"time"`
	Zhouqi int    `json:"zhouqi"`
}

func SetConfig(cfg *ConfigCli, inipath string) error {
	/*
		conf := goini.SetConfig(inipath)

		st := conf.SetValue("client", "shutdowntime", cfg.ShutdownTime)
		lt := conf.SetValue("client", "lunxuntime", fmt.Sprintf("%d", cfg.LunXunTime))
	*/
	inifile, _ := ini.Load(inipath)
	clisection, _ := inifile.GetSection("client")
	clisection.Key("shutdowntime").SetValue(cfg.ShutdownTime)
	clisection.Key("lunxuntime").SetValue(fmt.Sprintf("%d", cfg.LunXunTime))
	return inifile.SaveTo(inipath)

}
